package com.yonyou.jrmob.lryapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.application.bean.HomeMessageBean;
import com.yonyou.jrmob.application.ui.fragment.MainAppFragment;
import com.yonyou.jrmob.contacts.contact.fragment.ContactsMainFragment_ct;
import com.yonyou.jrmob.lryapp.fragment.MyFragment;
import com.yonyou.jrmob.lryapp.vo.AppAuth;
import com.yonyou.uap.emm.http.HttpCallback;
import com.yonyou.uap.emm.util.EmmUtil;
import com.yonyou.uap.emm.util.PhoneInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.HttpUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.login.bean.LoginBean;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;
import jrmob.yonyou.com.commonlib.vo.AppVO_ap;


public class MainActivity extends BaseActivityMob_lib {
    private static final int FINISHED_CALL_WEB_APP = 1;
    @BindView(R.id.main_fragment_container)
    FrameLayout mainFragmentContainer;
    @BindView(R.id.main_navigation_bar)
    BottomNavigationView mainNavigationBar;
    FragmentManager fm;
    private MainAppFragment mainAppFragment;
    private ContactsMainFragment_ct contactsMainFragmentCt;
    private boolean isExit = false;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FINISHED_CALL_WEB_APP){
                initFragment();
            }
        }
    };
    private UserInfoLRY userInfoLRY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Intent intent = getIntent();

        String toObject = intent.getStringExtra("toObject");
        Gson gson = new Gson();
        LoginBean object = gson.fromJson(toObject,LoginBean.class);
        userInfoLRY = (UserInfoLRY) intent.getSerializableExtra("userInfoLRY");

        saveDataToLocal(object);
        saveTaskListToLoccal(object);


        StatusBarUtil.setStatusBarColor(this,R.color.login_titlebar);

        initNav();
        // 刚进来加载所有应用列表
        loadapplistinfo(true);
        checkVersion();
        tempStatus = 1;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 保存首页task 列表
     * @param loginBean 登录接口返回的结果
     */
    private void saveTaskListToLoccal(LoginBean loginBean) {
        List<LoginBean.TaskListBean> messageBeanList = loginBean.getTask_list();
        writeLocationObject(Constant.task_list, messageBeanList);
        EventBus.getDefault().post("finised");
    }

    /**
     * 保存小部件的对应的数值
     * @param loginBean 登录接口返回的结果
     */
    private void saveDataToLocal(LoginBean loginBean) {

        String customer_count = loginBean.getCustomer_count();
        String payment_count = loginBean.getPayment_count();
        String contract_money = loginBean.getContract_money();
        String task_count = loginBean.getTask_count();

        userInfoLRY.setContract_money(contract_money);
        userInfoLRY.setPayment_count(payment_count);
        userInfoLRY.setCustomer_count(customer_count);
        userInfoLRY.setTask_count(task_count);

        writeLocationObject(Constant.userInfoLry, userInfoLRY);

        writeLocationFile(Constant.payment_count, payment_count);
        writeLocationFile(Constant.customer_count, customer_count);
        writeLocationFile(Constant.contract_money, contract_money);
        writeLocationFile(Constant.task_count, task_count);

        List<LoginBean.AppAuthBean> appAuths = loginBean.getAppAuth();

        writeLocationObject(Constant.app_auth, appAuths);

    }


    private void initFragment() {
        mainAppFragment = new MainAppFragment();
        contactsMainFragmentCt = new ContactsMainFragment_ct();
        fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.main_fragment_container, mainAppFragment).commit();
    }

    private void initNav() {
        mainNavigationBar.setItemIconTintList(null);
        mainNavigationBar.setItemTextColor(getResources().getColorStateList(R.color.selector_nav_color));
        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_press);
        mainNavigationBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_main_main_page:
                        item.setIcon(R.drawable.icon_main_page_press);
                        mainNavigationBar.getMenu().getItem(2).setIcon(R.drawable.icon_my_normal);
                        mainNavigationBar.getMenu().getItem(1).setIcon(R.drawable.icon_contacts_normal);
                        fm.beginTransaction().replace(R.id.main_fragment_container, mainAppFragment).commit();
                        break;
                    case R.id.menu_main_contact:

                        //showMessage("有待开发");
                        item.setIcon(R.drawable.icon_contacts_press);
                        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_normal);
                        mainNavigationBar.getMenu().getItem(2).setIcon(R.drawable.icon_my_normal);
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, contactsMainFragmentCt).commit();
//
                        break;
                    case R.id.menu_main_my:
                        item.setIcon(R.drawable.icon_my_press);
                        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_normal);
                        mainNavigationBar.getMenu().getItem(1).setIcon(R.drawable.icon_contacts_normal);
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new MyFragment()).commit();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        if (LRYApplication.model == null || TextUtils.isEmpty(LRYApplication.model)) {
            PhoneInfo info = new PhoneInfo(this);
            LRYApplication.model = info.getModel();
        }
    }

    //监听返回键

    @Override
    public void onBackPressed() {
        exit();
    }
    private void exit(){
        if (!isExit){
            isExit = true ;
            Toast.makeText(mActivity, "再按一次退出应用程序！", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            },2000);
        }else {
            System.exit(0);
        }
    }

    /*********** 加载 emm 上面的应用列表 start *********/



    /**
     * 加载applistinfo
     */
    public void loadapplistinfo(final boolean isupdate) {
        // 获取列表信息
        JSONObject json = new JSONObject();
        try {
            String user = Constant.emmUserName;
            // 利用登录账号读取 emm 应用信息
            String  usercode_rzzl = readLocationValue("usercode_rzzl");
            if (!TextUtils.isEmpty(usercode_rzzl)){
                //user = usercode_rzzl;
            }
            if (!TextUtils.isEmpty(user)) {
                json.put("userid", user);
                json.put("deviceid", MobUtils.getDeviceId(this));
                json.put("os", "android");
                // 标识是否立即更新
                getAppList(this, "none", json, callback2);
            }



        } catch (Exception e) {
            LogUtils.e(e);
        }


    }


    /**
     * @param context
     * @param tp       加密类型
     * @param data     数据  参数 JSONObject data = new JSONObject();
     *                 p.put("userid", "");
     *                 p.put("deviceid", "");
     *                 p.put("os", "android");
     * @param callBack
     */
    public void getAppList(Context context, final String tp, final JSONObject data, final HttpCallback callBack) {

        //10.15.0.111:8010
        Map map = BaseApp_lib.getMap_app();

        map.put("emm_ip",Constant.emmIP);
        map.put("emm_port",Constant.emmPORT);

        String emm_emm = map.get("emm_ip")+":"+map.get("emm_port");

        LogUtils.e("emm_emm: "+emm_emm);
        if (!TextUtils.isEmpty(emm_emm)) {
            final String url =  "http://" +emm_emm + "/mobem/app/getapps";
            LogUtils.e(url);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EmmUtil.getRequest(url, tp, data.toString(), callBack);
                    } catch (Exception e) {
                        LogUtils.e(e);
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }



    HttpCallback callback2 = new HttpCallback() {
        @Override
        public void execute(String s) {

            //LogUtils.e(s);
            if (null != s) {
                try {
                    JSONObject json = new JSONObject(s);
                    String tp = json.optString("tp", "none");
                    String data = json.optString("data", "");
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsondata = new JSONObject(data);
                        String code = jsondata.optString("code", "");
                        String msg = jsondata.optString("msg", "");
                        JSONArray apps = jsondata.optJSONArray("apps");
                        LogUtils.e("apps: " + apps);

                        if (null != apps) {
                            // 数据为空的时候不处理
                            if (apps.length() == 0) {
                                return;
                            }

                            BaseApp_lib.setAppslist(null);
                            BaseApp_lib.setAppslist(new ArrayList<AppVO_ap>());
                            JSONObject jsonObject;
                            List<AppVO_ap> tempappList = BaseApp_lib.getAppslist();
                            for (int i = 0; i < apps.length(); i++) {
                                AppVO_ap vo = new AppVO_ap();
                                jsonObject = apps.getJSONObject(i);

                                vo.setAppname(jsonObject.optString("title", ""));
                                vo.setAppid(jsonObject.optString("applicationId", ""));
                                vo.setAppcode(jsonObject.optString("title", ""));
                                vo.setApptype("0");
                                vo.setWebzipurl(jsonObject.optString("webzipurl", ""));
                                vo.setWebiconurl(jsonObject.optString("webiconurl", ""));
                                vo.setWebversion(jsonObject.optString("webversion", ""));
                                vo.setApptype("2");
                                tempappList.add(vo);
                            }



                            List<AppVO_ap> appslist = BaseApp_lib.getAppslist();
                            if (appslist.size()!=0){ // 说明有 h5的应用
                                orderApps(appslist);
                            }
                        }
                    } else {

                    }
                    Message message = Message.obtain();
                    message.what = FINISHED_CALL_WEB_APP;
                    mHandler.sendMessage(message);

                } catch (Exception e) {
                    LogUtils.e(e);
                }
            }
        }
    };

    /**
     * 对H5应用进行排序
     * 思路：首先申请一个list，长度为{appAuths，appsList， appAuth.sort}中的最大值，list的每一个原素先置位空，然后调用list.add(appAuth.sort, APPVO)
     * 这样就给原有的appsList排好序了，排好序后把里面的null剔除掉
     * @param appslist
     */
    private void orderApps(List<AppVO_ap> appslist) {
        ArrayList<LoginBean.AppAuthBean> appAuths = readLocationObject(Constant.app_auth, ArrayList.class);
        if (appAuths == null || appAuths.size() == 0){
            return;
        }
        ArrayList<AppVO_ap> tempOrderedAppVO_aps = new ArrayList<>();

        //获取最大值
        int authSortMax = 0;
        for (LoginBean.AppAuthBean appAuth : appAuths) {
            if (!TextUtils.isEmpty(appAuth.getApp_sort())){
                authSortMax = Math.max(authSortMax, Integer.parseInt(appAuth.getApp_sort()));
            }
        }
        int max = Math.max(appAuths.size(), appslist.size());
        max = Math.max(max, authSortMax);

        //申请一个长度为最大值的list，每一个元素都为null
        for (int i = 0; i < max; i++) {
            tempOrderedAppVO_aps.add(null);
        }
        //排序
        for (LoginBean.AppAuthBean appAuth : appAuths) {
            for (AppVO_ap appVO_ap : appslist) {
                if (appVO_ap.getAppid().equals(appAuth.getApp_code())){
                    tempOrderedAppVO_aps.add(Integer.parseInt(appAuth.getApp_sort()), appVO_ap);
                }
            }
        }

        //剔除空的元素
        Iterator<AppVO_ap> iterator = tempOrderedAppVO_aps.iterator();
        while (iterator.hasNext()){
            AppVO_ap appVOAp = iterator.next();
            if (appVOAp == null){
                iterator.remove();
            }
        }

        AppVO_ap appVO_ap0 = new AppVO_ap();
        appVO_ap0.setAppname(Constant.EXTRA_H5_APP);
        appVO_ap0.setAppid("mifeng");
        tempOrderedAppVO_aps.add(appVO_ap0);

        AppVO_ap appVO_ap1 = new AppVO_ap();
        appVO_ap1.setAppname(Constant.EXTRA_H5_YIDONGSHENPI);
        appVO_ap1.setAppid("yidongshenpi");
        tempOrderedAppVO_aps.add(appVO_ap1);
        // 写到本地
        writeLocationObject(Constant.appsinfo, tempOrderedAppVO_aps);
    }


    /*********** 加载 emm 上面的应用列表 end *********/


    /*********************自动更新**********************/
    /**
     * 功能: 检查版本更新
     * <p/>
     * 日 期: 2016/7/14
     */
    private void checkVersion() {

        if (!CommonUtil.isNetworkConnected(this)) {
            Toast.makeText(mActivity, "当前网络不可用，请检查！", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    Object result = HttpUtil.sendPost("https://appstore.yonyou.com/sites/update.php",
                            "type=apk&&name=" + getResources().getString(R.string.description));

                    Message message = Message.obtain();
                    message.what = 90000;
                    message.obj = result;

                    handler.sendMessage(message);
                }
            }).start();
        } catch (Exception e) {
            LogUtils.e("eeee: " + e);
        }
    }

        android.os.Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what ){

                    case 90000:

                        // 校验
                        checkJudeyApkVersion(msg.obj+"");

                        break;

                    default:

                        break;
                }
            }

        };


    private void checkJudeyApkVersion(String info){

        try {
            LogUtils.e(info+"");
            JSONObject json = new JSONObject(info);
            int code = json.optInt("code",1);
            String message = json.optString("msg","错误");
            String versionCode = json.optString("versionCode","1.0");
            String update_url = json.optString("update_url","www.baidu.com");
            String update_msg = json.optString("update_msg","更新出错啦!");
            //username.setText(msg.obj+"");
            if(message.equals("检测更新成功")) {
                //保存下载地址和版本
                updateVersionInfo(update_url, versionCode);
                //检查版本
                if (checkupdateVersion()) {
                    new android.support.v7.app.AlertDialog.Builder(this)
                            .setTitle(update_msg)
                            .setMessage("检测到有新的版本,是否更新到" + versionCode + "版本")
                            .setNegativeButton(
                                    "更新",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                            String update_url = readLocationValue("update_url");

                                            LogUtils.e("从本地读取update_url = " + update_url);
                                            if (!TextUtils.isEmpty(update_url)) {
                                                updateAppVersion(update_url);
                                            } else {
                                                mActivity.showToast("更新路径URL有误!");
                                            }
                                        }

                                    })
                            .setPositiveButton(
                                    "取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            dialog.dismiss();
                                                    /*Message message = Message.obtain();
                                                    message.what = 0; // 登录成功
                                                    // 不需要更新
                                                    handler.sendMessage(message);*/

                                        }
                                    }).setCancelable(false).show();
                }
            }else{
                showToast("检测更新失败");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新升级版本
     * update_url apk现在地址
     * versioncode 新的apk对应的版本号
     */
    private void updateVersionInfo(String update_url,String versioncode){

        // 记录下,后台的版本信息
        writeLocationFile("app_version",versioncode+"");
        writeLocationFile("update_url",update_url);

    }


    /**
     * 检查更新
     */
    private boolean checkupdateVersion() {

        String app_version = readLocationValue("app_version");
        if (!TextUtils.isEmpty(app_version)) {
            if (!TextUtils.isEmpty(getVersionName())){
                float oldversion = Float.valueOf(getVersionName());
                float newversion = Float.valueOf(app_version);
                // 判断是否需要更新
                if (newversion > oldversion) {
                    return true;
                }
            }else{
                return false;
            }

        }
        return false;
    }


    /**
     * 更新app,转到url
     * @param url
     */
    private void  updateAppVersion(String url){
        // 不为空,到升级网址
        if (!TextUtils.isEmpty(url)){
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
        }
    }


/*********************自动更新结束**********************/
    }
